import uc from '@/api/uc.js'
import auth from '@/api/auth.js'

// 获取当前sessionStorage中存放的用户信息
const getCurrentUserFromStorage = () => {
  const user = sessionStorage.getItem('currentUser')
  if (user != 'null' && user != undefined && user != '') {
    return JSON.parse(user)
  }
  return null
}

// 设置用户信息到sessionStorage中
const setCurrentUserToStorage = user => {
  sessionStorage.setItem('currentUser', JSON.stringify(user))
}

// 清空sessionStorage中的用户信息
const cleanCurrentUserInStorage = () => {
  sessionStorage.removeItem('currentUser')
}

const state = {
  currentUser: getCurrentUserFromStorage(),
  loginAccount: null,
  isRefreshToken: false,
  loginStatus: true,
  loginValue: {}
}

const getters = {}

const actions = {
  actionLoginAccount({commit, state}, loginAccount) {
    commit('mutationLoginAccount', loginAccount)
  },
  loginByPrincipal({commit, state}, principal) {
    return new Promise((resolve, reject) => {
      auth.authentication(
        principal,
        user => {
          if (user) {
            commit('setLoginValue', user.value)
            // 当前登录毫秒数
            user.loginTime = new Date().getTime()
            setCurrentUserToStorage(user)
            commit('setCurrentUser', user)
            resolve(user)
          }
        },
        msg => {
          commit('clearCurrentUser')
          reject(msg)
        }
      )
    })
  },
  refreshAndGetAuthenticationToken({commit, state}) {
    if (state.isRefreshToken) {
      return
    }
    commit('isRefreshToken', true)
    return new Promise((resolve, reject) => {
      auth.refreshAndGetAuthenticationToken().then(
        user => {
          if (user) {
            setCurrentUserToStorage(user)
            commit('refreshToken', user.token)
            setTimeout(() => {
              commit('isRefreshToken', false)
            }, 3000)
            resolve()
          }
        },
        msg => {
          reject(msg)
        }
      )
    })
  },
  validAndCompletedCurrent({commit, state}, token) {
    return new Promise((resolve, reject) => {
      if (state.currentUser && !token) {
        resolve()
      } else if (token) {
        auth.basicSso(
          token,
          user => {
            setCurrentUserToStorage(user)
            commit('setCurrentUser', user)
            resolve()
          },
          () => {
            reject()
          }
        )
      } else {
        reject()
      }
    })
  },
  logoutAndCleanUp({commit, state}) {
    return new Promise((resolve, reject) => {
      auth.logout().finally(() => {
        cleanCurrentUserInStorage()
        commit('clearCurrentUser')
        commit('user/setCurrentUserDetail', null, {root: true})
        resolve()
      })
    })
  },
  cleanCurrentUser({commit, state}) {
    cleanCurrentUserInStorage()
    commit('clearCurrentUser')
    commit('user/setCurrentUserDetail', null, {root: true})
  },
  async twoStepVerify({commit, dispatch}, loginInfo) {
    const formData = new FormData()
    formData.append('code', loginInfo.code)
    formData.append('token', loginInfo.token)
    const {
      data: {value}
    } = await uc.twoStepVerify(formData)
    value.loginTime = new Date().getTime()
    commit('setLoginStatus', value.loginStatus)
    setCurrentUserToStorage(value)
    commit('setCurrentUser', value)
  }
}

const mutations = {
  isRefreshToken(state, status) {
    state.isRefreshToken = status
  },
  refreshToken(state, token) {
    state.currentUser.token = token
    state.currentUser.loginTime = new Date().getTime()
  },
  setCurrentUser(state, current) {
    state.currentUser = current
  },
  setLoginValue(state, loginValue) {
    state.loginValue = loginValue
  },
  clearCurrentUser(state) {
    state.currentUser = null
  },
  mutationLoginAccount(state, loginAccount) {
    state.loginAccount = loginAccount
  },
  setLoginStatus(state, loginStatus) {
    state.loginStatus = loginStatus
  }
}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}
